from fastapi import APIRouter, Query,UploadFile,Request
from tortoise.expressions import Q

from app.controllers.appointment.category import category_controller
from app.controllers.appointment.project import appointment_project_controller
from app.controllers.appointment.space import appointment_space_controller
from app.controllers.goods.sku import sku_controller
from app.controllers.system.user import user_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.appointment import *
from app.settings import settings
from app.core.redis_base import delete_keys, redis_get
from app.models.appointment import AppointmentCategory, AppointmentProject
from app.utils.upload import upload_image

appointment_project_router = APIRouter()
model_name = "预约项目"


@appointment_project_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    # user = await user_controller.get(user_id)
    # if user.space_id:
    #     q &= Q(space_id=user.space_id)
    if name:
        q &= Q(name__contains=name)
    total, data = await appointment_project_controller.do_list(page=page, page_size=page_size, search=q)
    category_objs = await appointment_project_controller.categorys()
    for item in data:
        item["type_name"] = category_objs[item["type"]]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)
@appointment_project_router.get("/get_projects", summary="获取项目列表")
async def do_get_projects(
        request: Request,
        category_id: int = Query(0, description="项目分类:1预约项目2搭配项目"),
        space_id: int = Query(1, description="门店id"),
        name: str = Query(None, description="商品名称"),
):
    data = await redis_get(f"projects:projects{space_id}_{category_id}", request.state.redis)
    if data is None:
        # 判断门店的项目ids
        space = await appointment_space_controller.do_detail(space_id)
        space_project_roles = space['project_roles']
        ##获取预约项目大类
        q1 = Q()
        if category_id > 0:
            q1 &= Q(parent_id=category_id)

        q2 = Q()
        if space_project_roles:
            q2 &= Q(id__in=space_project_roles)
        data = await AppointmentCategory.filter(q1).all().values("id", "name", "desc")
        for item in data:
            q3 = q2 & Q(type=item['id'])
            q3 &= Q(status=1)
            if name:
                q3 &= Q(name__contains=name)
            total, project_data = await appointment_project_controller.do_list(page=1, page_size=100, search=q3)
            item["projects"] = project_data
            item["label"] = item['name']
            item["value"] = item['id']
            item["children"] = project_data
        ##await redis_set(f"projects:projects{space_id}_{type_id}_{d_type_id}_{doctor_id}", data, request.state.redis)
    return SuccessExtra(data=data)

@appointment_project_router.post("/price", summary="获取时长和金额", dependencies=[DependCustomerAuth])
async def do_price(
        request: Request,
        data_in: AppointmentGetPrice,
):
    user_id = CTX_USER_ID.get()
    project_id = data_in.project_id
    projects_all = []
    if data_in.ex_project_ids:
        ex_project_ids = data_in.ex_project_ids.copy()  ##[2,3]
        projects_all = ex_project_ids
    projects_all.append(project_id)  ##1,2,3
    ex_data = await AppointmentProject.filter(id__in=projects_all).values("id", "sku_id", "interval")
    longs = 0
    price = 0
    for item in ex_data:
        longs += item["interval"]
        if item["sku_id"]:
            sku_price = await sku_controller.get_price_by_user(sku_id=item["sku_id"], user_id=user_id)
        else:
            sku_price = 0
        price += sku_price
    price = price * data_in.come_nums
    data = {
        "longs": longs,
        "price": price,
    }
    return SuccessExtra(data=data)

@appointment_project_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await appointment_project_controller.do_detail(data_id=data_id)
    return Success(data=data)

@appointment_project_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        request: Request,
        data_in: AppointmentProjectCreate,
):
    await appointment_project_controller.do_create(request,obj_in=data_in)
    return Success(msg="创建成功")

@appointment_project_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        request: Request,
        data_in: AppointmentProjectUpdate,
):
    await appointment_project_controller.do_update(request,obj_in=data_in)
    return Success(msg="更新成功")

@appointment_project_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        request: Request,
        data_id: int = Query(..., description="ID"),
):
    await appointment_project_controller.do_delete(request,data_id=data_id)
    return Success(msg="删除成功")

# @appointment_project_router.get("/project", summary="获取项目分类")
# async def list_level():
#     level_objs = settings.APPOINTMENT_PROJECT
#     data = []
#     key = 0
#     for level in level_objs:
#         if level:
#             data.append({"label":level,"value":key})
#         key += 1
#     return Success(data=data)

@appointment_project_router.get("/project", summary="树形分类")
async def tree_dept():
    data = await category_controller.get_tree()
    datas = [{
        "id": 0,
        "name": "全部",
        "desc": "全部",
        "order": 1,
        "parent_id": -1,
        "children": data,  # 递归构建子部门
    }]
    return SuccessExtra(data=datas)

@appointment_project_router.get("/tree", summary="获取项目配置树")
async def list_tree():
    level_objs = await AppointmentCategory.filter(parent_id__gt=0).all().values()
    data = []
    key = 0
    for level in level_objs:
        if level["id"]:
            children = await appointment_project_controller.level_list(type=level["id"])
            data.append({"label":level["name"],"value":key+10000,"children":children})
        key += 1
    return Success(data=data)

@appointment_project_router.post("/file", summary="上传图片")
async def do_file(file: UploadFile):
    url = await upload_image(file,"appointment/project")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)